import { SubscribeMessage, WebSocketGateway, WebSocketServer, OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
import { Server, WebSocket } from 'ws';

@WebSocketGateway() // 指定ws端口号，不配置则默认与http服务相同端口
export class WsGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
    @WebSocketServer()
    server: Server;

    // 初始化后执行
    afterInit(server: Server) {
        console.log('WebSocket server initialized');
    }

    // 处理新连接
    handleConnection(client: WebSocket, ...args: any[]) {
        console.log('Client connected:');
    }

    // 处理断开连接
    handleDisconnect(client: WebSocket) {
        console.log(`Client disconnected: ${client}`);
    }

    // 消息处理示例
    @SubscribeMessage('message') // 这里的message对应的是前端发送ws请求的里的event值
    handleMessage(client: WebSocket, payload: any): string {
        console.log('handleMessage message:', payload);
        client.send(JSON.stringify({ event: 'message', data: `我收到了你发的消息${payload}` })); // 回发消息
        return 'OK';
    }
}
